import {
    RequestConfig
} from './../types';

import {
    checkPost
} from './../utils';

import agent from './agent';

import * as sign from './sign';

import * as Token from '../token';

import * as Env from './../../env';

import * as fcm from '../../utils/fcm';

import * as Channel from  './../../utils/channel';

const apiUrl = async () => (
    await Env.apiBaseUrl() + `/v2`
)

export default async (
    config: RequestConfig
):Promise<RequestConfig> => {
    const {
        url,
        method,
        headers,
    } = config;

    const _key_ = (
        checkPost(method) ? `data` : `params`
    )

    const _data_ = config[_key_] || {};

    _data_.engine = Env.engine;

    const _query = (
        await sign.query(method, _data_)
    )

    try {
        headers[`token`] = (
            await Token.get()
        )
        headers[`deviceToken`] = (
            await fcm.getToken()
        )
        headers[`Custom-Agent`] = (
            await agent()
        )
        headers[`channel`] = (
            await Channel.getChannel()
        )
    }
    catch (e) {
        return Promise.reject(e);
    }

    const reSendPara = {
        url:url,
        method:method,
        [_key_]:_data_
    }

    return {
        ...config,
        [_key_]:_data_,
        reSendPara:reSendPara,
        url: `${url}?${_query}`,
        baseURL: await apiUrl()
    };
}